package com.sunny.openplatformutils.utils;

import java.io.IOException;
import java.util.List;

import org.apache.http.Header;
import org.apache.http.client.fluent.Request;
import org.apache.http.entity.ContentType;

/**
 * 
 * @author Sunny
 *
 */
public class HttpUtil {
	
	private HttpUtil() {
	}

	private static int connectTimeout = 3000, socketTimeout = 3000;
	
	public static void configTimeout(int connectTimeout, int socketTimeout) {
		HttpUtil.connectTimeout = connectTimeout;
		HttpUtil.socketTimeout = socketTimeout;
	}

	public static String get(String uri) throws IOException {
		return get(uri, null);
	}
	
	public static String get(String uri, List<Header> headers) throws IOException {
		Request request = Request.Get(uri)
				.connectTimeout(connectTimeout)
				.socketTimeout(socketTimeout);
		
		addHeader(request, headers);
		return request.execute().returnContent().asString();
	}
	
	public static String post(String uri, List<Header> headers, String jsonBody) throws IOException {
		Request request = Request.Post(uri)
				.connectTimeout(connectTimeout)
				.socketTimeout(connectTimeout);
		
		addHeader(request, headers);
		request.bodyString(jsonBody, ContentType.APPLICATION_JSON);
		return request.execute().returnContent().asString();
	}
	
	private static void addHeader(Request request, List<Header> headers) {
		if (headers != null && headers.size() > 0) {
			for (Header header : headers) {
				request.addHeader(header);
			}
		}
	}

}
